package com.dcliu.db;

import java.util.List;
import org.apache.ibatis.session.SqlSession;

public class SQLDao{

	private static final String ROW_COUNT_ = "_Row_Count";

	public SQLDao(){};
    
    private SqlSession session4Write;
    
    private SqlSession session4Read;
    
    public <T> T selectOne(String statement)
    {
        return session4Read.selectOne(statement);
    }

    public <T> T selectOne(String statement, Object param)
    {
        return session4Read.selectOne(statement, param);
    }

    public <T> List<T> select(String statement)
    {
        return session4Read.selectList(statement);
    }

    public <T> List<T> select(String statement, Object param)
    {
        return session4Read.selectList(statement, param);
    }
    
    public int insert(String statement)
    {
        return session4Write.insert(statement);
    }

    public int insert(String statement, Object param)
    {
        return session4Write.insert(statement, param);
    }

    public int update(String statement)
    {
        return session4Write.update(statement);
    }

    public int update(String statement, Object param)
    {
        return session4Write.update(statement, param);
    }

    public int delete(String statement)
    {
        return session4Write.delete(statement);
    }

    public int delete(String statement, Object param)
    {
        return session4Write.delete(statement, param);
    }

    public <T> Page<T> selectPage(String statement, PageRequest param)
    {
        Page<T> page = new Page<T>();
        Integer count = (Integer)selectOne((new StringBuilder())
        		.append(statement).append(ROW_COUNT_).toString(), param);
        if(count != null && count.intValue() > 0)
        {
            List<T> result = select(statement, param);
            page.setResult(result);
        } 
        else{
            count = Integer.valueOf(0);
        }
        page.setPage(param.getPage());
        page.setSize(param.getSize());
        page.setCount(count.intValue());
        return page;
    }

    public void setSession4Write(SqlSession session4Write)
    {
        this.session4Write = session4Write;
    }

    public void setSession4Read(SqlSession session4Read)
    {
        this.session4Read = session4Read;
    }

}